<?php
/**
 * Created by PhpStorm.
 * User: ruma
 * Date: 2019/1/21
 * Time: 16:41
 */

namespace app\admin\model;


use app\admin\validate\CategoryValidate;
use app\admin\validate\DeleteCategoryValidate;
use app\common\model\AdminBaseModel;
use app\Excepiton\DatabaseException;

class Category extends AdminBaseModel
{
    protected $pk = 'cate_id';
    protected $table = 'category';

//    public function article(){
//        return $this->hasMany('Article','')
//    }

    public function store(){
        $this->insert();
        //1.验证并获取提交信息
        $postData = (new CategoryValidate())->postCheckAndGet();
        //2.执行添加
        $result = $this->save($postData);
        if (!$result){
            throw new DatabaseException([
                'msg' => '数据添加失败'
            ]);
        }
        return true;
    }


    //无限级分类
    public function getAllCate(){
        $arr = $this->order('cate_sort desc')->select()->toArray();
        $array = GetTree($arr);
        return $array;
    }

    /**
     * 获取可以编辑的分类
     */

    public function getCateEditData($cid){
        $cate = $this->select()->toArray();
        //1.获取子集数据
        $cids = $this->getSon($cate,$cid);
        //2.将子集id和自己的pid
        $cids[] = $cid;
        //3.找到除了自己相关的数据
        $field = $this->whereNotIn('cate_id',$cids)->select()->toArray();
        $arr = GetTree($field);
        return $arr;
    }


    /**
    * 获取所有分类的子集cid
    */
    public function getSon($cate,$cid){
        static $result = [];
        foreach ($cate as $key=>$value){
            if ($cid == $value['pid']){
                array_push($result,$value['cate_id']);
                $this->getSon($cate,$value['cate_id']);
            }
        }
        return $result;
    }

    /**
     * 编辑栏目
     */

    public function editCate(){
        //1.验证并post信息
        $data = (new CategoryValidate())->postCheckAndGet();
        //2.根据提交的cid改变其它属性[name,pid,sort]
        $result = $this->update($data,$data['cate_id']);
        if(!$result){
            throw new DatabaseException();
        }
        return true;
    }

    /**
     * 删除栏目
     */
    public function del(){
        //1.获取提交的信息
        $postData = (new DeleteCategoryValidate())->postCheckAndGet();
        $cid = $postData['cate_id'];
        $pid = $postData['pid'];
        //2.将其子元素的PID更新成自己的PID,并且删除自己
        $update = $this->update(['pid'=>$pid],['pid'=>$cid]);
        $del = $this->where('cate_id','=',$cid)->delete();
        if (!$update || !$del){
            throw new DatabaseException();
        }
        return true;
    }
}

